package com.auto.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class NIOClient {
    public static void main(String[] args) throws Exception {
        //创建SocketChannel --> socket
        SocketChannel socketChannel = SocketChannel.open();
        //设置为非阻塞
        socketChannel.configureBlocking(false);
        //指定ip和端口号
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);

        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {
            //连接不成功
            while (!socketChannel.finishConnect()) {
                //如果没有完成连接
                System.out.println("端连接需要事件，客户端不会阻塞，可以做其他事情");
            }
            String str = "hello NIO入门";
            //wrap读取字节数据，生成的ByteBuffer的长度和字节数据长度相同，节省资源
            ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
            //将数据写入通道channel中
            socketChannel.write(byteBuffer);
        }
        System.in.read();
    }
}
